package com.yssoft.utils;

import com.yssoft.entity.core.ComparedResult;
import com.yssoft.entity.core.TEnterprise;
import com.yssoft.entity.core.TcCompanyModify;
import com.yssoft.mapper.core.TAccountsMapper;
import com.yssoft.service.core.EnterpriseService;
import com.yssoft.service.sales.TcCompanyModifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 企业信息修改 工具类
 *
 * @author wmh
 * @date 2024-05-27 10:00:35
 */
@Component
public class CompanyModifyUtil {
    private static final Logger logger = LoggerFactory.getLogger(CompanyModifyUtil.class);

    /* 企业信息修改 Service*/
    @Resource
    private TcCompanyModifyService tcCompanyModifyService;
    private static TcCompanyModifyService companyModifyService;

    /* 许可主体 Service*/
    @Resource
    private EnterpriseService tcCompanyService;
    private static EnterpriseService companyService;

    @PostConstruct
    private void init() {
        companyModifyService = tcCompanyModifyService;
        companyService = tcCompanyService;
    }

    /**
     * 企业信息修改记录
     *
     * @param entity            操作的实体类
     * @param operationType     操作类型（0-新增;1-修改;2-删除）
     * @param operationDescribe 操作描述
     * @param primaryId         新增操作主键id
     * @param <T>
     */
    public static <T> void companyModify(T entity, String changeMaterials, String operationType, String operationDescribe, Long primaryId) {
        List<ComparedResult> resultList = new ArrayList<>();
        Integer id = null;
        String comName = "";
        try {
            // 获取当前类的 Class 对象
            Class<T> entityClass = (Class<T>) entity.getClass();
            // 获取当前实体类的名称
            String entityName = entityClass.getSimpleName();
            // 获取当前对象所有的属性，包括父类中的属性
            Field[] fiels = entityClass.getDeclaredFields();
            for (Field f : fiels) {
                // 设置可访问私有属性，默认是不可访问的
                f.setAccessible(true);
                // 获取属性名
                String fieldName = f.getName();
                // 获取属性值
                Object fieldValue = f.get(entity);
                if ("id".equals(fieldName)) {
                    id = (Integer) fieldValue;

                }
                if ("companyName".equals(fieldName)) {
                    comName = String.valueOf(fieldValue);
                }
            }
            logger.info("企业信息修改 id==>" + id);

            switch (entityName) {
                case "TEnterprise":
                    if ("0".equals(operationType)) {
                        resultList = CompareUtil.addComparedResult(entity);
                    } else if ("1".equals(operationType)) {
                        TEnterprise companyEntity = companyService.queryEnterpriseById(id);
                        comName = companyEntity.getName();
                        resultList = CompareUtil.compareTwoObject(companyEntity, entity);
                    }

                    TcCompanyModify tcme = modifyEntity(id, operationType, comName, operationDescribe, primaryId, resultList);
                    tcme.setChangeMaterials(changeMaterials);
                    if (tcme != null) {
                        boolean b = companyModifyService.addTcCompanyModify(tcme);
                        logger.info("企业信息修改 记录入库结果 -> {}", b);
                    } else {
                        logger.info("企业信息修改 无字段变化，不记录本次 {} 操作", operationDescribe);
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 企业信息修改实体类拼装
     *
     * @param id                操作id
     * @param operationType     操作类型（0-新增;1-修改;2-删除）
     * @param companyName       操作企业名称
     * @param operationDescribe 操作描述
     * @param primaryId         新增操作主键id
     * @param resultList        操作内容
     * @return
     */
    private static TcCompanyModify modifyEntity(Integer id, String operationType, String companyName, String operationDescribe, Long primaryId, List<ComparedResult> resultList) {
        TcCompanyModify tcCompanyModifyEntity = new TcCompanyModify();
        if (CollectionUtils.isEmpty(resultList) && !"2".equals(operationType)) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
//        sb.append(companyName + " " + operationDescribe + " -> ");
        StringBuilder oldChange = new StringBuilder();
        StringBuilder newChange = new StringBuilder();
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < resultList.size(); i++) {
            sb.append(resultList.get(i).getRemark());
            if (resultList.get(i).getFieldName() != null && resultList.get(i).getNewValue() != null) {
                content.append(resultList.get(i).getFieldName());
                content.append("；");
            }
            if (resultList.get(i).getOldValue() != null && resultList.get(i).getNewValue() != null) {
                oldChange.append(isUtilDate(resultList.get(i).getOldValue()));
                oldChange.append("；");
            }
            if (resultList.get(i).getNewValue() != null) {
                newChange.append(isUtilDate(resultList.get(i).getNewValue()));
                sb.append("；");
                newChange.append("；");
            }

        }

        tcCompanyModifyEntity.setTeId("0".equals(operationType) ? primaryId : id);
        tcCompanyModifyEntity.setCreateTime(new Date());
        tcCompanyModifyEntity.setOldChange(oldChange.toString());
        tcCompanyModifyEntity.setNewChange(newChange.toString());
        tcCompanyModifyEntity.setContent(content.toString());
        tcCompanyModifyEntity.setOperationType(operationType);

        logger.info("企业信息修改 实体类内容-->" + tcCompanyModifyEntity);
        return tcCompanyModifyEntity;
    }

    //检查字段类型并进行日期格式化
    private static Object isUtilDate(Object data) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (data instanceof Date) {
            String format = dateFormat.format((Date) data);
            return format;
        } else {
            return data;
        }

    }


}
